package com.dodock.banglapapers.server.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.*;
import org.jsoup.select.Elements;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DDNNewsDetailProthomAlo {

	
	public String Generate(String newsid) throws IOException{
		//
		// Get a handle on the datastore itself
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();		
		// Lookup data by known key name
		try {
			Entity detailsEntity = datastore.get(KeyFactory.createKey("NewsDetails", "prothomalo__"+newsid));
			Text text = (Text)detailsEntity.getProperty("data");
			return text.getValue();
			
		} catch (EntityNotFoundException e) {
			
			Document doc = Jsoup.connect(Settings.WWW_PROTHOM_ALO_COM + "/" + newsid).timeout(30000).get();
			
			JsonObject news = new JsonObject();
			news.addProperty("id", newsid);
			Element content = doc.select("div[class^=jw_detail_content_holder]").first();
			
			
			JsonArray imageGallery = new JsonArray();
			Elements galleryImages = content.select("img[class^=jwMediaContent]");
			for(Element img:galleryImages){
				JsonObject image = new JsonObject();
				image.addProperty("url", img.attr("src"));
				imageGallery.add(image);
				img.remove();
			}
			if(imageGallery.size() > 0){
				news.add("gallery", imageGallery);
			}
			
			news.addProperty("details", content.html().replace("\n", "").replace("&nbsp;", " "));
			news.addProperty("sharelink", Settings.WWW_PROTHOM_ALO_COM + "/" + newsid);
			
			String data = news.toString();
			Text text = new Text(data);
			/* save here */
			Entity detailsEntity = new Entity("NewsDetails", "prothomalo__"+newsid);
			detailsEntity.setProperty("data", text);
			datastore.put(detailsEntity);
			return data;
				
		}
		
		
	}
	
	
}
